package main

import (
	"github.com/XieWeikai/PlaceToGo/controllers"
	"github.com/XieWeikai/PlaceToGo/middlewares"
	"github.com/XieWeikai/PlaceToGo/models"
	"log"
	"net/http"
	"os"

	"github.com/gin-gonic/gin"
	"github.com/joho/godotenv"
)

func main() {
	err := godotenv.Load(".env")
	if err != nil {
		log.Fatal("Error loading .env file")
	}

	models.InitModel()

	uploadDir := os.Getenv("UPLOAD_DIR")
	err = os.MkdirAll(uploadDir, os.ModePerm)
	if err != nil {
		log.Fatal("Cannot create upload directory", err)
	}

	r := gin.Default()
	r.Use(middlewares.CORSMiddleware())

	r.GET("/", func(c *gin.Context) {
		c.Redirect(http.StatusPermanentRedirect, "/page/index.html")
	})

	r.POST("/users", controllers.Register)
	r.POST("/auth", controllers.Login)

	auth := r.Group("/")
	r.GET("/users/:id", controllers.GetUser)
	r.GET("/users", controllers.GetUsers)
	r.GET("/requests/:id", controllers.GetRequest)
	r.GET("/requests", controllers.GetRequests)

	auth.Use(middlewares.JwtAuthMiddleware())

	auth.POST("/logout", controllers.Logout)
	auth.POST("/upload", controllers.Upload)
	auth.POST("/requests", controllers.CreateRequest)
	auth.POST("/responses", controllers.CreateResponse)
	auth.POST("/accept/:responseId", controllers.AcceptResponse)

	auth.GET("/responses/:id", controllers.GetResponse)
	auth.GET("/responses", controllers.GetResponses)
	auth.GET("/broker_summary", controllers.GetBrokerSummary)
	auth.GET("/broker_summary_by_time", controllers.GetBrokerSummaryByTime)

	auth.PUT("/responses/:id", controllers.UpdateResponse)
	auth.PUT("/users/:id", controllers.UpdateUser)
	auth.PUT("/requests/:id", controllers.UpdateRequest)

	auth.DELETE("/requests/:id", controllers.CancelRequest)
	auth.DELETE("/responses/:id", controllers.CancelResponse)

	r.Static("/data", uploadDir)
	r.Static("/page", "./dist")

	port := os.Getenv("PORT")
	log.Panic(r.Run(":" + port))
}
